package com.lindroy.androidplayer.logic.network

import com.elvishew.xlog.XLog
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import com.ihsanbal.logging.Level
import com.ihsanbal.logging.LoggingInterceptor
import com.lindroy.androidplayer.base.App
import com.lindroy.networkrequestpractice.logic.network.base.BaseRetrofitBuilder
import okhttp3.CookieJar
import okhttp3.OkHttpClient
import okhttp3.internal.platform.Platform

/**
 * @author Lin
 * @date 2021/10/19
 * @function
 */
private const val LOG_TAG_HTTP_REQUEST = "okhttp_request"
private const val LOG_TAG_HTTP_RESULT = "okhttp_result"

object RetrofitBuilder : BaseRetrofitBuilder() {

    private var cookieJar:PersistentCookieJar? = null

    override fun handleOkHttpClientBuilder(builder: OkHttpClient.Builder) {
        cookieJar =   PersistentCookieJar(
            SetCookieCache(),
            SharedPrefsCookiePersistor(App.context)
        )
        cookieJar?.also {  builder.cookieJar(it) }
    }

    override fun initLoggingInterceptor() = LoggingInterceptor
        .Builder()
        .setLevel(Level.BASIC)
        .log(Platform.INFO)
        .request(LOG_TAG_HTTP_REQUEST)
        .response(LOG_TAG_HTTP_RESULT)
        .build()

    /**
     * 退出登录时清除 cookie
     */
    fun clearCookie() = cookieJar?.clear()
}